package com.audaque.springboot.foshanupload.web.config;

/**
 * @author zgb
 * @desc ...
 * @date 2022-01-27 22:56:14
 */

import com.audaque.springboot.foshanupload.web.listener.ContextClosedEventListener;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(value = "server.ssl.enabled",havingValue = "true",matchIfMissing = false)
public class Http2HttpsConfig {

    @Value("${http.httpPortForHttps}")
    private int port;

    @Value("${server.ssl.port}")
    private int sslPort;

    @Autowired
    private ContextClosedEventListener contextClosedEventListener;

    @Bean
    public TomcatServletWebServerFactory containerFactory() {
        CustomTomcatServletWebServerFactory customTomcatServletWebServerFactory = new CustomTomcatServletWebServerFactory();
        /**
         * 经过前面  HTTPS  配置以后，如果我们再用  HTTP  的方式访问接口，会发现访问失败。这是因为  Spring Boot  不支持同时在配置中启动  HTTP  和  HTTPS。
         * 实现：http转发到https,实现http和https兼容
         * 配置完成后，我们在浏览器上输入 “http://localhost:80/hello” 就会自动重定向到“https://localhost:8081/hello”
         */
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(port);
        connector.setSecure(false);
        connector.setRedirectPort(sslPort);
        customTomcatServletWebServerFactory.addAdditionalTomcatConnectors(connector);
        customTomcatServletWebServerFactory.addConnectorCustomizers(contextClosedEventListener);
        return customTomcatServletWebServerFactory;
    }

    static final class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/**");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }

    }



}
